package com.dotmedia.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dotmedia.dboperations.AdvertiserDatabaseOperations;
import com.dotmedia.entities.Advertiser;
import com.dotmedia.utils.StringUtils;

/**
 * This servlet is for finding out whether or not an advertiser id already exist in the database or not. This is used in the add new ad form when
 * submitting.
 * 
 * An AJAX request will be made to this servlet to find out whether the advertiser id mentioned on the add new ad is valid or not. If it is not valid
 * then the form will not be submitted.
 * 
 * This servlet will need the following parameter - <code>advertiserId</code> This servlet will return <code>exists</code> if the advertiser id exists
 * else it will return <code>not.exists</code>
 */
public class AdvertiserIdValidationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger("dotmedia.servlets");
	private static final String ADVERTISER_ID_PARAMETER = "advertiserId"; // this is the parameter to be read
	private static final String RESULT_EXISTS = "exists";
	private static final String RESULT_NOT_EXISTS = "not.exists";
	private static final String CONTENT_TYPE_TEXT = "text/html";
	private static final String ENDING_BRACKET = "]";
	private static final String STARTING_BRACKET = "[";

	public AdvertiserIdValidationServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	/**
	 * This method will service the request to this servlet.
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("IN servlet AdvertiserIdValidationServlet");
		response.setContentType(CONTENT_TYPE_TEXT);
		String result = RESULT_NOT_EXISTS;
		String advertiserIdParam = (String) request.getParameter(ADVERTISER_ID_PARAMETER);
		// get the advertiser id from this - it will be of the form Advertiser1[some-description][advertiser-id]
		boolean isValidated = true;
		if (StringUtils.isStringNull(advertiserIdParam)) {
			logger.error("The required parameter " + ADVERTISER_ID_PARAMETER + " received is null. Nothing to do");
		} else {
			if (advertiserIdParam.endsWith(ENDING_BRACKET)) {
				// then it is fine else not fine
				advertiserIdParam = advertiserIdParam.substring(0, advertiserIdParam.length() - 1);
				int indexOfLastStartBracket = advertiserIdParam.lastIndexOf(STARTING_BRACKET);
				if (indexOfLastStartBracket == -1) {
					logger.error(STARTING_BRACKET + " does not exist in the advertiser id. Nothing to do");
					isValidated = false;
				} else {
					advertiserIdParam = advertiserIdParam.substring(indexOfLastStartBracket + 1);
					logger.info("AdvertiserId extracted to process is " + advertiserIdParam);
				}
			} else {
				logger.error("The AdvertiserId received does not end with " + ENDING_BRACKET + ". The received AdvertiserId is: " + advertiserIdParam);
				isValidated = false;
			}
			if (isValidated) {
				int advertiserId = -1;
				try {
					advertiserId = Integer.parseInt(advertiserIdParam);
					// it is validated - now to see whether this advertiser id exists or not
					AdvertiserDatabaseOperations advertiserDatabaseOperations = new AdvertiserDatabaseOperations();
					List<Advertiser> advertiserEntities = advertiserDatabaseOperations.getAdvertiserEntitiesByAdvertiserId(advertiserId);
					if (advertiserEntities != null) {
						for (Advertiser currentAdvertiserEntity : advertiserEntities) {
							if (currentAdvertiserEntity.getAdvertiserId().intValue() == advertiserId) {
								logger.info("An Advertiser entity with the id " + advertiserId + " exists");
								result = RESULT_EXISTS;
								break;
							}
						}
					}
				} catch (NumberFormatException numberFormatException) {
					logger.error("The advertiserId received is not an integer. Nothing to do. advertiserId received = " + advertiserIdParam);
				}
			} else {
				result = RESULT_NOT_EXISTS;
			}
		}
		// write the result back to the client
		logger.info("Writing back results. Results = " + result); 
		response.getOutputStream().println(result);
		response.getOutputStream().flush();
		logger.info("OUT servlet AdvertiserIdValidationServlet");
	}

}
